<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
	 protected function _initView(){
        $this->bootstrap('layout');
        $layout = $this->getResource('layout');
        $view = $layout->getView();        
        $view->addHelperPath(APPLICATION_PATH.'/../library/Zext/View/Helper/');        
        return $view;
    }
    
    
    protected function _initAcl(){
        
        // Start Caching
        $frontendOptions = array(
           'lifetime' => 7200,
           'automatic_serialization' => true
        );
         
        $backendOptions = array(
            'cache_dir' => CACHE_PATH
        );
     
        // getting a Zend_Cache_Core object
        $cache = Zend_Cache::factory( 'Core', 'File', $frontendOptions, $backendOptions );
        
        // get init db form bootstrap
        $db = $this->getPluginResource('db')
                   ->getDbAdapter();
        
        // Check database update acl
        $appOption = new Application_Model_DbTable_CauHinh( array('db' => $db) );
        $appOption->updateCache( $cache );
        
        
        if(!$acl = $cache->load( 'TrachNhiem' )) {            
            // init Zend_Acl    
           	$acl = new Zend_Acl();		
            
           // Add the Role          
            $modelRole = new Application_Model_DbTable_NhomTaiKhoan( array('db' => $db) );
    		$rowsRole = $modelRole->fetchAll();
    		foreach($rowsRole as $rowRole){
    			$acl->addRole(new Zend_Acl_Role($rowRole->MaNhom));
    		}
            // Add default role (GUEST)
            $default_role = new Zend_Acl_Role(GUEST_ID);
            if(!$acl->hasRole( $default_role )){
                $acl->addRole( $default_role );
            }
            
            // Add the Resource
    		$modelResource = new Application_Model_DbTable_NghiepVu( array('db' => $db) );
            $rowsResource = $modelResource->fetchAll();
            foreach($rowsResource as $rowResource){
                $acl->add( new Zend_Acl_Resource( $rowResource->MaNghiepVu ) );
            }
            
            
            // Setting for Zend_Acl allow or deny
    		$modelAllow = new Application_Model_DbTable_TrachNhiem( array('db' => $db) );
    		$rowsAllow = $modelAllow->fetchAll();
    		$acl->deny(); // Default deny all
    		foreach($rowsAllow as $row)
    		{
    			if($row->ChoPhep)
    			{
    				$acl->allow(
                        new Zend_Acl_Role( $row->MaNhom ),
                        new Zend_Acl_Resource( $row->MaNghiepVu )
                    );
    			}
            }    
            // Save the cache core
            $cache->save( $acl, "Zend_Acl_dbTrachNhiem" );
        }        
		Zend_Registry::set('acl', $acl);
        Zend_Registry::set('cache', $cache);
        
    }
}
